home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 4: GNU Archives / Linux Cubed Series 4 - GNU Archives.iso / gnu / git-4.3 / git-4 / git-4.3.11 / src / history.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-04-22  |  47.8 KB  |  2,022 lines

  1. /* history.c -- Standalone history library.  */
  2.  
  3. /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
  4.  
  5.    This file contains the GNU History Library (the Library), a set of
  6.    routines for managing the text of previously typed lines.
  7.  
  8.    The Library is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 1, or (at your option)
  11.    any later version.
  12.  
  13.    The Library is distributed in the hope that it will be useful, but
  14.    WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.    General Public License for more details.
  17.  
  18.    The GNU General Public License is often shipped with GNU software, and
  19.    is generally kept in a file called COPYING or LICENSE.  If you do not
  20.    have a copy of the license, write to the Free Software Foundation,
  21.    675 Mass Ave, Cambridge, MA 02139, USA. */
  22.  
  23. /* The goal is to make the implementation transparent, so that you
  24.    don't have to know what data types are used, just what functions
  25.    you can call.  I think I have done that. */
  26. #define READLINE_LIBRARY
  27.  
  28. #ifdef HAVE_CONFIG_H
  29. #include <config.h>
  30. #endif
  31.  
  32. #include <stdio.h>
  33. #include <sys/types.h>
  34. #include "file.h"
  35. #include "xio.h"
  36.  
  37. #if defined (HAVE_STDLIB_H)
  38. #  include <stdlib.h>
  39. #else
  40. #  include "ansi_stdlib.h"
  41. #endif /* HAVE_STDLIB_H */
  42.  
  43. #if defined (HAVE_UNISTD_H)
  44. #  include <unistd.h>
  45. #endif
  46.  
  47. #include "xstring.h"
  48.  
  49. #include <errno.h>
  50.  
  51. /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
  52. #if !defined (errno)
  53. extern int errno;
  54. #endif /* !errno */
  55.  
  56. #include "history.h"
  57.  
  58. #include "xmalloc.h"
  59.  
  60. #define STREQ(a, b)     (((a)[0] == (b)[0]) && (strcmp ((a), (b)) == 0))
  61. #define STREQN(a, b, n) (((a)[0] == (b)[0]) && (strncmp ((a), (b), (n)) == 0))
  62.  
  63. #ifndef savestring
  64. #  ifndef strcpy
  65. extern char *strcpy ();
  66. #  endif
  67. #define savestring(x) strcpy (xmalloc (1 + strlen (x)), (x))
  68. #endif
  69.  
  70. #ifndef whitespace
  71. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  72. #endif
  73.  
  74. #ifndef digit
  75. #define digit(c)  ((c) >= '0' && (c) <= '9')
  76. #endif
  77.  
  78. #ifndef digit_value
  79. #define digit_value(c) ((c) - '0')
  80. #endif
  81.  
  82. #ifndef member
  83. #  ifndef strchr
  84. extern char *strchr ();
  85. #  endif
  86. #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
  87. #endif
  88.  
  89. /* Possible history errors passed to hist_error. */
  90. #define EVENT_NOT_FOUND 0
  91. #define BAD_WORD_SPEC   1
  92. #define SUBST_FAILED    2
  93. #define BAD_MODIFIER    3
  94.  
  95. static char error_pointer;
  96.  
  97. static char *subst_lhs;
  98. static char *subst_rhs;
  99. static int subst_lhs_len = 0;
  100. static int subst_rhs_len = 0;
  101.  
  102. static char *get_history_word_specifier ();
  103.  
  104. #if defined (SHELL)
  105. extern char *single_quote ();
  106. #endif
  107.  
  108. /* **************************************************************** */
  109. /*                                                                  */
  110. /*                      History Functions                           */
  111. /*                                                                  */
  112. /* **************************************************************** */
  113.  
  114. /* An array of HIST_ENTRY.  This is where we store the history. */
  115. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  116.  
  117. /* Non-zero means that we have enforced a limit on the amount of
  118.    history that we save. */
  119. int history_stifled = 0;
  120.  
  121. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  122.    entries to remember. */
  123. int max_input_history;
  124.  
  125. /* The current location of the interactive history pointer.  Just makes
  126.    life easier for outside callers. */
  127. static int history_offset = 0;
  128.  
  129. /* The number of strings currently stored in the input_history list. */
  130. int history_length = 0;
  131.  
  132. /* The current number of slots allocated to the input_history. */
  133. static int history_size = 0;
  134.  
  135. /* The number of slots to increase the_history by. */
  136. #define DEFAULT_HISTORY_GROW_SIZE 50
  137.  
  138. /* The character that represents the start of a history expansion
  139.    request.  This is usually `!'. */
  140. char history_expansion_char = '!';
  141.  
  142. /* The character that invokes word substitution if found at the start of
  143.    a line.  This is usually `^'. */
  144. char history_subst_char = '^';
  145.  
  146. /* During tokenization, if this character is seen as the first character
  147.    of a word, then it, and all subsequent characters upto a newline are
  148.    ignored.  For a Bourne shell, this should be '#'.  Bash special cases
  149.    the interactive comment character to not be a comment delimiter. */
  150. char history_comment_char = '\0';
  151.  
  152. /* The list of characters which inhibit the expansion of text if found
  153.    immediately following history_expansion_char. */
  154. char *history_no_expand_chars = " \t\n\r=";
  155.  
  156. /* The logical `base' of the history array.  It defaults to 1. */
  157. int history_base = 1;
  158.  
  159. /* Return the current HISTORY_STATE of the history. */
  160. HISTORY_STATE *
  161. history_get_history_state ()
  162. {
  163.   HISTORY_STATE *state;
  164.  
  165.   state = (HISTORY_STATE *)xmalloc (sizeof (HISTORY_STATE));
  166.   state->entries = the_history;
  167.   state->offset = history_offset;
  168.   state->length = history_length;
  169.   state->size = history_size;
  170.  
  171.   return (state);
  172. }
  173.  
  174. /* Set the state of the current history array to STATE. */
  175. void
  176. history_set_history_state (state)
  177.      HISTORY_STATE *state;
  178. {
  179.   the_history = state->entries;
  180.   history_offset = state->offset;
  181.   history_length = state->length;
  182.   history_size = state->size;
  183. }
  184.  
  185. /* Begin a session in which the history functions might be used.  This
  186.    initializes interactive variables. */
  187. void
  188. using_history ()
  189. {
  190.   history_offset = history_length;
  191. }
  192.  
  193. /* Return the number of bytes that the primary history entries are using.
  194.    This just adds up the lengths of the_history->lines. */
  195. int
  196. history_total_bytes ()
  197. {
  198.   register int i, result;
  199.  
  200.   result = 0;
  201.  
  202.   for (i = 0; the_history && the_history[i]; i++)
  203.     result += strlen (the_history[i]->line);
  204.  
  205.   return (result);
  206. }
  207.  
  208. /* Place STRING at the end of the history list.  The data field
  209.    is  set to NULL. */
  210. void
  211. add_history (string)
  212.      char *string;
  213. {
  214.   HIST_ENTRY *temp;
  215.  
  216.   if (history_stifled && (history_length == max_input_history))
  217.     {
  218.       register int i;
  219.  
  220.       /* If the history is stifled, and history_length is zero,
  221.      and it equals max_input_history, we don't save items. */
  222.       if (history_length == 0)
  223.     return;
  224.  
  225.       /* If there is something in the slot, then remove it. */
  226.       if (the_history[0])
  227.     {
  228.       xfree (the_history[0]->line);
  229.       xfree (the_history[0]);
  230.     }
  231.  
  232.       /* Copy the rest of the entries, moving down one slot. */
  233.       for (i = 0; i < history_length; i++)
  234.     the_history[i] = the_history[i + 1];
  235.  
  236.       history_base++;
  237.  
  238.     }
  239.   else
  240.     {
  241.       if (!history_size)
  242.     {
  243.       history_size = DEFAULT_HISTORY_GROW_SIZE;
  244.       the_history = (HIST_ENTRY **)xmalloc (history_size * sizeof (HIST_ENTRY *));
  245.       history_length = 1;
  246.  
  247.     }
  248.       else
  249.     {
  250.       if (history_length == (history_size - 1))
  251.         {
  252.           history_size += DEFAULT_HISTORY_GROW_SIZE;
  253.           the_history = (HIST_ENTRY **)
  254.         xrealloc (the_history, history_size * sizeof (HIST_ENTRY *));
  255.         }
  256.       history_length++;
  257.     }
  258.     }
  259.  
  260.   temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  261.   temp->line = savestring (string);
  262.   temp->data = (char *)NULL;
  263.  
  264.   the_history[history_length] = (HIST_ENTRY *)NULL;
  265.   the_history[history_length - 1] = temp;
  266. }
  267.  
  268. /* Make the history entry at WHICH have LINE and DATA.  This returns
  269.    the old entry so you can dispose of the data.  In the case of an
  270.    invalid WHICH, a NULL pointer is returned. */
  271. HIST_ENTRY *
  272. replace_history_entry (which, line, data)
  273.      int which;
  274.      char *line;
  275.      char *data;
  276. {
  277.   HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  278.   HIST_ENTRY *old_value;
  279.  
  280.   if (which >= history_length)
  281.     return ((HIST_ENTRY *)NULL);
  282.  
  283.   old_value = the_history[which];
  284.  
  285.   temp->line = savestring (line);
  286.   temp->data = data;
  287.   the_history[which] = temp;
  288.  
  289.   return (old_value);
  290. }
  291.  
  292. /* Returns the magic number which says what history element we are
  293.    looking at now.  In this implementation, it returns history_offset. */
  294. int
  295. where_history ()
  296. {
  297.   return (history_offset);
  298. }
  299.  
  300. /* Search the history for STRING, starting at history_offset.
  301.    If DIRECTION < 0, then the search is through previous entries, else
  302.    through subsequent.  If ANCHORED is non-zero, the string must
  303.    appear at the beginning of a history line, otherwise, the string
  304.    may appear anywhere in the line.  If the string is found, then
  305.    current_history () is the history entry, and the value of this
  306.    function is the offset in the line of that history entry that the
  307.    string was found in.  Otherwise, nothing is changed, and a -1 is
  308.    returned. */
  309.  
  310. #define ANCHORED_SEARCH 1
  311. #define NON_ANCHORED_SEARCH 0
  312.  
  313. static int
  314. history_search_internal (string, direction, anchored)
  315.      char *string;
  316.      int direction, anchored;
  317. {
  318.   register int i, reverse;
  319.   register char *line;
  320.   register int line_index;
  321.   int string_len;
  322.  
  323.   i = history_offset;
  324.   reverse = (direction < 0);
  325.  
  326.   /* Take care of trivial cases first. */
  327.  
  328.   if (!history_length || ((i == history_length) && !reverse))
  329.     return (-1);
  330.  
  331.   if (reverse && (i == history_length))
  332.     i--;
  333.  
  334. #define NEXT_LINE() do { if (reverse) i--; else i++; } while (0)
  335.  
  336.   string_len = strlen (string);
  337.   while (1)
  338.     {
  339.       /* Search each line in the history list for STRING. */
  340.  
  341.       /* At limit for direction? */
  342.       if ((reverse && i < 0) || (!reverse && i == history_length))
  343.     return (-1);
  344.  
  345.       line = the_history[i]->line;
  346.       line_index = strlen (line);
  347.  
  348.       /* If STRING is longer than line, no match. */
  349.       if (string_len > line_index)
  350.     {
  351.       NEXT_LINE ();
  352.       continue;
  353.     }
  354.  
  355.       /* Handle anchored searches first. */
  356.       if (anchored == ANCHORED_SEARCH)
  357.     {
  358.       if (STREQN (string, line, string_len))
  359.         {
  360.           history_offset = i;
  361.           return (0);
  362.         }
  363.  
  364.       NEXT_LINE ();
  365.       continue;
  366.     }
  367.  
  368.       /* Do substring search. */
  369.       if (reverse)
  370.     {
  371.       line_index -= string_len;
  372.  
  373.       while (line_index >= 0)
  374.         {
  375.           if (STREQN (string, line + line_index, string_len))
  376.         {
  377.           history_offset = i;
  378.           return (line_index);
  379.         }
  380.           line_index--;
  381.         }
  382.     }
  383.       else
  384.     {
  385.       register int limit = line_index - string_len + 1;
  386.       line_index = 0;
  387.  
  388.       while (line_index < limit)
  389.         {
  390.           if (STREQN (string, line + line_index, string_len))
  391.         {
  392.           history_offset = i;
  393.           return (line_index);
  394.         }
  395.           line_index++;
  396.         }
  397.     }
  398.       NEXT_LINE ();
  399.     }
  400. }
  401.  
  402. /* Do a non-anchored search for STRING through the history in DIRECTION. */
  403. int
  404. history_search (string, direction)
  405.      char *string;
  406.      int direction;
  407. {
  408.   return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
  409. }
  410.  
  411. /* Do an anchored search for string through the history in DIRECTION. */
  412. int
  413. history_search_prefix (string, direction)
  414.      char *string;
  415.      int direction;
  416. {
  417.   return (history_search_internal (string, direction, ANCHORED_SEARCH));
  418. }
  419.  
  420. /* Remove history element WHICH from the history.  The removed
  421.    element is returned to you so you can free the line, data,
  422.    and containing structure. */
  423. HIST_ENTRY *
  424. remove_history (which)
  425.      int which;
  426. {
  427.   HIST_ENTRY *return_value;
  428.  
  429.   if (which >= history_length || !history_length)
  430.     return_value = (HIST_ENTRY *)NULL;
  431.   else
  432.     {
  433.       register int i;
  434.       return_value = the_history[which];
  435.  
  436.       for (i = which; i < history_length; i++)
  437.     the_history[i] = the_history[i + 1];
  438.  
  439.       history_length--;
  440.     }
  441.  
  442.   return (return_value);
  443. }
  444.  
  445. /* Stifle the history list, remembering only MAX number of lines. */
  446. void
  447. stifle_history (max)
  448.      int max;
  449. {
  450.   if (max < 0)
  451.     max = 0;
  452.  
  453.   if (history_length > max)
  454.     {
  455.       register int i, j;
  456.  
  457.       /* This loses because we cannot free the data. */
  458.       for (i = 0; i < (history_length - max); i++)
  459.     {
  460.       xfree (the_history[i]->line);
  461.       xfree (the_history[i]);
  462.     }
  463.  
  464.       history_base = i;
  465.       for (j = 0, i = history_length - max; j < max; i++, j++)
  466.     the_history[j] = the_history[i];
  467.       the_history[j] = (HIST_ENTRY *)NULL;
  468.       history_length = j;
  469.     }
  470.  
  471.   history_stifled = 1;
  472.   max_input_history = max;
  473. }
  474.  
  475. /* Stop stifling the history.  This returns the previous amount the history
  476.  was stifled by.  The value is positive if the history was stifled, negative
  477.  if it wasn't. */
  478. int
  479. unstifle_history ()
  480. {
  481.   int result = max_input_history;
  482.  
  483.   if (history_stifled)
  484.     {
  485.       result = -result;
  486.       history_stifled = 0;
  487.     }
  488.  
  489.   return (result);
  490. }
  491.  
  492. /* Return the string that should be used in the place of this
  493.    filename.  This only matters when you don't specify the
  494.    filename to read_history (), or write_history (). */
  495. static char *
  496. history_filename (filename)
  497.      char *filename;
  498. {
  499.   char *return_val = filename ? savestring (filename) : (char *)NULL;
  500.  
  501.   if (!return_val)
  502.     {
  503.       char *home;
  504.       int home_len;
  505.  
  506.       home = getenv ("HOME");
  507.  
  508.       if (!home)
  509.     home = ".";
  510.  
  511.       home_len = strlen (home);
  512.       /* strlen(".history") == 8 */
  513.       return_val = xmalloc (2 + home_len + 8);
  514.  
  515.       strcpy (return_val, home);
  516.       return_val[home_len] = '/';
  517.       strcpy (return_val + home_len + 1, ".history");
  518.     }
  519.  
  520.   return (return_val);
  521. }
  522.  
  523. /* Add the contents of FILENAME to the history list, a line at a time.
  524.    If FILENAME is NULL, then read from ~/.history.  Returns 0 if
  525.    successful, or errno if not. */
  526. int
  527. read_history (filename)
  528.      char *filename;
  529. {
  530.   return (read_history_range (filename, 0, -1));
  531. }
  532.  
  533. /* Read a range of lines from FILENAME, adding them to the history list.
  534.    Start reading at the FROM'th line and end at the TO'th.  If FROM
  535.    is zero, start at the beginning.  If TO is less than FROM, read
  536.    until the end of the file.  If FILENAME is NULL, then read from
  537.    ~/.history.  Returns 0 if successful, or errno if not. */
  538. int
  539. read_history_range (filename, from, to)
  540.      char *filename;
  541.      int from, to;
  542. {
  543.   register int line_start, line_end;
  544.   char *input, *buffer = (char *)NULL;
  545.   int file, current_line;
  546.   struct stat finfo;
  547.  
  548.   input = history_filename (filename);
  549.   file = open (input, O_RDONLY, 0666);
  550.  
  551.   if ((file < 0) || (xfstat (file, &finfo) == -1))
  552.     goto error_and_exit;
  553.  
  554.   buffer = xmalloc ((int)finfo.st_size + 1);
  555.  
  556.   if (read (file, buffer, finfo.st_size) != finfo.st_size)
  557.     {
  558.   error_and_exit:
  559.       if (file >= 0)
  560.     close (file);
  561.  
  562.       if (input)
  563.     xfree (input);
  564.  
  565.       if (buffer)
  566.     xfree (buffer);
  567.  
  568.       return (errno);
  569.     }
  570.  
  571.   close (file);
  572.  
  573.   /* Set TO to larger than end of file if negative. */
  574.   if (to < 0)
  575.     to = finfo.st_size;
  576.  
  577.   /* Start at beginning of file, work to end. */
  578.   line_start = line_end = current_line = 0;
  579.  
  580.   /* Skip lines until we are at FROM. */
  581.   while (line_start < finfo.st_size && current_line < from)
  582.     {
  583.       for (line_end = line_start; line_end < finfo.st_size; line_end++)
  584.     if (buffer[line_end] == '\n')
  585.       {
  586.         current_line++;
  587.         line_start = line_end + 1;
  588.         if (current_line == from)
  589.           break;
  590.       }
  591.     }
  592.  
  593.   /* If there are lines left to gobble, then gobble them now. */
  594.   for (line_end = line_start; line_end < finfo.st_size; line_end++)
  595.     if (buffer[line_end] == '\n')
  596.       {
  597.     buffer[line_end] = '\0';
  598.  
  599.     if (buffer[line_start])
  600.       add_history (buffer + line_start);
  601.  
  602.     current_line++;
  603.  
  604.     if (current_line >= to)
  605.       break;
  606.  
  607.     line_start = line_end + 1;
  608.       }
  609.  
  610.   if (input)
  611.     xfree (input);
  612.  
  613.   if (buffer)
  614.     xfree (buffer);
  615.  
  616.   return (0);
  617. }
  618.  
  619. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  620.    If FNAME is NULL, then use ~/.history. */
  621. int
  622. history_truncate_file (fname, lines)
  623.      char *fname;
  624.      register int lines;
  625. {
  626.   register int i;
  627.   int file, chars_read;
  628.   char *buffer = (char *)NULL, *filename;
  629.   struct stat finfo;
  630.  
  631.   filename = history_filename (fname);
  632.   file = open (filename, O_RDONLY, 0666);
  633.  
  634.   if (file == -1 || xfstat (file, &finfo) == -1)
  635.     goto truncate_exit;
  636.  
  637.   buffer = xmalloc ((int)finfo.st_size + 1);
  638.   chars_read = read (file, buffer, finfo.st_size);
  639.   close (file);
  640.  
  641.   if (chars_read <= 0)
  642.     goto truncate_exit;
  643.  
  644.   /* Count backwards from the end of buffer until we have passed
  645.      LINES lines. */
  646.   for (i = chars_read - 1; lines && i; i--)
  647.     {
  648.       if (buffer[i] == '\n')
  649.     lines--;
  650.     }
  651.  
  652.   /* If this is the first line, then the file contains exactly the
  653.      number of lines we want to truncate to, so we don't need to do
  654.      anything.  It's the first line if we don't find a newline between
  655.      the current value of i and 0.  Otherwise, write from the start of
  656.      this line until the end of the buffer. */
  657.   for ( ; i; i--)
  658.     if (buffer[i] == '\n')
  659.       {
  660.     i++;
  661.     break;
  662.       }
  663.  
  664.   /* Write only if there are more lines in the file than we want to
  665.      truncate to. */
  666.   if (i && ((file = open (filename, O_WRONLY|O_TRUNC, 0666)) != -1))
  667.     {
  668.       write (file, buffer + i, finfo.st_size - i);
  669.       close (file);
  670.     }
  671.  
  672.  truncate_exit:
  673.   if (buffer)
  674.     xfree (buffer);
  675.  
  676.   xfree (filename);
  677.   return 0;
  678. }
  679.  
  680. #define HISTORY_APPEND 0
  681. #define HISTORY_OVERWRITE 1
  682.  
  683. /* Workhorse function for writing history.  Writes NELEMENT entries
  684.    from the history list to FILENAME.  OVERWRITE is non-zero if you
  685.    wish to replace FILENAME with the entries. */
  686. static int
  687. history_do_write (filename, nelements, overwrite)
  688.      char *filename;
  689.      int nelements, overwrite;
  690. {
  691.   register int i;
  692.   char *output = history_filename (filename);
  693.   int file, mode;
  694.  
  695.   mode = overwrite ? O_WRONLY | O_CREAT | O_TRUNC : O_WRONLY | O_APPEND;
  696.  
  697.   if ((file = open (output, mode, 0666)) == -1)
  698.     {
  699.       if (output)
  700.     xfree (output);
  701.  
  702.       return (errno);
  703.     }
  704.  
  705.   if (nelements > history_length)
  706.     nelements = history_length;
  707.  
  708.   /* Build a buffer of all the lines to write, and write them in one syscall.
  709.      Suggested by Peter Ho (peter@robosts.oxford.ac.uk). */
  710.   {
  711.     register int j = 0;
  712.     int buffer_size = 0;
  713.     char *buffer;
  714.  
  715.     /* Calculate the total number of bytes to write. */
  716.     for (i = history_length - nelements; i < history_length; i++)
  717.       buffer_size += 1 + strlen (the_history[i]->line);
  718.  
  719.     /* Allocate the buffer, and fill it. */
  720.     buffer = xmalloc (buffer_size);
  721.  
  722.     for (i = history_length - nelements; i < history_length; i++)
  723.       {
  724.     strcpy (buffer + j, the_history[i]->line);
  725.     j += strlen (the_history[i]->line);
  726.     buffer[j++] = '\n';
  727.       }
  728.  
  729.     write (file, buffer, buffer_size);
  730.     xfree (buffer);
  731.   }
  732.  
  733.   close (file);
  734.  
  735.   if (output)
  736.     xfree (output);
  737.  
  738.   return (0);
  739. }
  740.  
  741. /* Append NELEMENT entries to FILENAME.  The entries appended are from
  742.    the end of the list minus NELEMENTs up to the end of the list. */
  743. int
  744. append_history (nelements, filename)
  745.      int nelements;
  746.      char *filename;
  747. {
  748.   return (history_do_write (filename, nelements, HISTORY_APPEND));
  749. }
  750.  
  751. /* Overwrite FILENAME with the current history.  If FILENAME is NULL,
  752.    then write the history list to ~/.history.  Values returned
  753.    are as in read_history ().*/
  754. int
  755. write_history (filename)
  756.      char *filename;
  757. {
  758.   return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  759. }
  760.  
  761. /* Return the history entry at the current position, as determined by
  762.    history_offset.  If there is no entry there, return a NULL pointer. */
  763. HIST_ENTRY *
  764. current_history ()
  765. {
  766.   if ((history_offset == history_length) || !the_history)
  767.     return ((HIST_ENTRY *)NULL);
  768.   else
  769.     return (the_history[history_offset]);
  770. }
  771.  
  772. /* Back up history_offset to the previous history entry, and return
  773.    a pointer to that entry.  If there is no previous entry then return
  774.    a NULL pointer. */
  775. HIST_ENTRY *
  776. previous_history ()
  777. {
  778.   if (!history_offset)
  779.     return ((HIST_ENTRY *)NULL);
  780.   else
  781.     return (the_history[--history_offset]);
  782. }
  783.  
  784. /* Move history_offset forward to the next history entry, and return
  785.    a pointer to that entry.  If there is no next entry then return a
  786.    NULL pointer. */
  787. HIST_ENTRY *
  788. next_history ()
  789. {
  790.   if (history_offset == history_length)
  791.     return ((HIST_ENTRY *)NULL);
  792.   else
  793.     return (the_history[++history_offset]);
  794. }
  795.  
  796. /* Return the current history array.  The caller has to be carefull, since this
  797.    is the actual array of data, and could be bashed or made corrupt easily.
  798.    The array is terminated with a NULL pointer. */
  799. HIST_ENTRY **
  800. history_list ()
  801. {
  802.   return (the_history);
  803. }
  804.  
  805. /* Return the history entry which is logically at OFFSET in the history array.
  806.    OFFSET is relative to history_base. */
  807. HIST_ENTRY *
  808. history_get (offset)
  809.      int offset;
  810. {
  811.   int local_index = offset - history_base;
  812.  
  813.   if (local_index >= history_length ||
  814.       local_index < 0 ||
  815.       !the_history)
  816.     return ((HIST_ENTRY *)NULL);
  817.   return (the_history[local_index]);
  818. }
  819.  
  820. /* Search for STRING in the history list.  DIR is < 0 for searching
  821.    backwards.  POS is an absolute index into the history list at
  822.    which point to begin searching. */
  823. int
  824. history_search_pos (string, dir, pos)
  825.      char *string;
  826.      int dir, pos;
  827. {
  828.   int ret, old = where_history ();
  829.   history_set_pos (pos);
  830.   if (history_search (string, dir) == -1)
  831.     {
  832.       history_set_pos (old);
  833.       return (-1);
  834.     }
  835.   ret = where_history ();
  836.   history_set_pos (old);
  837.   return ret;
  838. }
  839.  
  840. /* Make the current history item be the one at POS, an absolute index.
  841.    Returns zero if POS is out of range, else non-zero. */
  842. int
  843. history_set_pos (pos)
  844.      int pos;
  845. {
  846.   if (pos > history_length || pos < 0 || !the_history)
  847.     return (0);
  848.   history_offset = pos;
  849.   return (1);
  850. }
  851.  
  852.  
  853. /* **************************************************************** */
  854. /*                                                                  */
  855. /*                      History Expansion                           */
  856. /*                                                                  */
  857. /* **************************************************************** */
  858.  
  859. /* Hairy history expansion on text, not tokens.  This is of general
  860.    use, and thus belongs in this library. */
  861.  
  862. /* The last string searched for in a !?string? search. */
  863. static char *search_string = (char *)NULL;
  864.  
  865. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  866.    point to after the event specifier.  Just a pointer to the history
  867.    line is returned; NULL is returned in the event of a bad specifier.
  868.    You pass STRING with *INDEX equal to the history_expansion_char that
  869.    begins this specification.
  870.    DELIMITING_QUOTE is a character that is allowed to end the string
  871.    specification for what to search for in addition to the normal
  872.    characters `:', ` ', `\t', `\n', and sometimes `?'.
  873.    So you might call this function like:
  874.    line = get_history_event ("!echo:p", &index, 0);  */
  875. char *
  876. get_history_event (string, caller_index, delimiting_quote)
  877.      char *string;
  878.      int *caller_index;
  879.      int delimiting_quote;
  880. {
  881.   register int i = *caller_index;
  882.   register char c;
  883.   HIST_ENTRY *entry;
  884.   int which, sign = 1;
  885.   int local_index, search_mode, substring_okay = 0;
  886.   char *temp;
  887.  
  888.   /* The event can be specified in a number of ways.
  889.  
  890.      !!   the previous command
  891.      !n   command line N
  892.      !-n  current command-line minus N
  893.      !str the most recent command starting with STR
  894.      !?str[?]
  895.       the most recent command containing STR
  896.  
  897.      All values N are determined via HISTORY_BASE. */
  898.  
  899.   if (string[i] != history_expansion_char)
  900.     return ((char *)NULL);
  901.  
  902.   /* Move on to the specification. */
  903.   i++;
  904.  
  905. #define RETURN_ENTRY(e, w) \
  906.     return ((e = history_get (w)) ? e->line : (char *)NULL)
  907.  
  908.   /* Handle !! case. */
  909.   if (string[i] == history_expansion_char)
  910.     {
  911.       i++;
  912.       which = history_base + (history_length - 1);
  913.       *caller_index = i;
  914.       RETURN_ENTRY (entry, which);
  915.     }
  916.  
  917.   /* Hack case of numeric line specification. */
  918.   if (string[i] == '-')
  919.     {
  920.       sign = -1;
  921.       i++;
  922.     }
  923.  
  924.   if (digit (string[i]))
  925.     {
  926.       /* Get the extent of the digits and compute the value. */
  927.       for (which = 0; digit (string[i]); i++)
  928.     which = (which * 10) + digit_value (string[i]);
  929.  
  930.       *caller_index = i;
  931.  
  932.       if (sign < 0)
  933.     which = (history_length + history_base) - which;
  934.  
  935.       RETURN_ENTRY (entry, which);
  936.     }
  937.  
  938.   /* This must be something to search for.  If the spec begins with
  939.      a '?', then the string may be anywhere on the line.  Otherwise,
  940.      the string must be found at the start of a line. */
  941.   if (string[i] == '?')
  942.     {
  943.       substring_okay++;
  944.       i++;
  945.     }
  946.  
  947.   /* Only a closing `?' or a newline delimit a substring search string. */
  948.   for (local_index = i; (c = string[i]); i++)
  949.     if ((!substring_okay && (whitespace (c) || c == ':' ||
  950. #if defined (SHELL)
  951.       member (c, ";&()|<>") ||
  952. #endif /* SHELL */
  953.       string[i] == delimiting_quote)) ||
  954.     string[i] == '\n' ||
  955.     (substring_okay && string[i] == '?'))
  956.       break;
  957.  
  958.   temp = xmalloc (1 + (i - local_index));
  959.   strncpy (temp, &string[local_index], (i - local_index));
  960.   temp[i - local_index] = '\0';
  961.  
  962.   if (substring_okay && string[i] == '?')
  963.     i++;
  964.  
  965.   *caller_index = i;
  966.  
  967. #define FAIL_SEARCH() \
  968.   do { history_offset = history_length; xfree (temp) ; return (char *)NULL; } while (0)
  969.  
  970.   search_mode = substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH;
  971.   while (1)
  972.     {
  973.       local_index = history_search_internal (temp, -1, search_mode);
  974.  
  975.       if (local_index < 0)
  976.     FAIL_SEARCH ();
  977.  
  978.       if (local_index == 0 || substring_okay)
  979.     {
  980.       entry = current_history ();
  981.       history_offset = history_length;
  982.  
  983.       /* If this was a substring search, then remember the
  984.          string that we matched for word substitution. */
  985.       if (substring_okay)
  986.         {
  987.           if (search_string)
  988.         xfree (search_string);
  989.           search_string = temp;
  990.         }
  991.       else
  992.         xfree (temp);
  993.       return (entry->line);
  994.     }
  995.  
  996.       if (history_offset)
  997.     history_offset--;
  998.       else
  999.     FAIL_SEARCH ();
  1000.     }
  1001. #undef FAIL_SEARCH
  1002. #undef RETURN_ENTRY
  1003. }
  1004. #if defined (SHELL)
  1005. /* Function for extracting single-quoted strings.  Used for inhibiting
  1006.    history expansion within single quotes. */
  1007.  
  1008. /* Extract the contents of STRING as if it is enclosed in single quotes.
  1009.    SINDEX, when passed in, is the offset of the character immediately
  1010.    following the opening single quote; on exit, SINDEX is left pointing
  1011.    to the closing single quote. */
  1012. static void
  1013. rl_string_extract_single_quoted (string, sindex)
  1014.      char *string;
  1015.      int *sindex;
  1016. {
  1017.   register int i = *sindex;
  1018.  
  1019.   while (string[i] && string[i] != '\'')
  1020.     i++;
  1021.  
  1022.   *sindex = i;
  1023. }
  1024.  
  1025. static char *
  1026. quote_breaks (s)
  1027.      char *s;
  1028. {
  1029.   register char *p, *r;
  1030.   char *ret;
  1031.   int len = 3;
  1032.  
  1033.   for (p = s; p && *p; p++, len++)
  1034.     {
  1035.       if (*p == '\'')
  1036.     len += 3;
  1037.       else if (whitespace (*p) || *p == '\n')
  1038.     len += 2;
  1039.     }
  1040.  
  1041.   r = ret = xmalloc (len);
  1042.   *r++ = '\'';
  1043.   for (p = s; p && *p; )
  1044.     {
  1045.       if (*p == '\'')
  1046.     {
  1047.       *r++ = '\'';
  1048.       *r++ = '\\';
  1049.       *r++ = '\'';
  1050.       *r++ = '\'';
  1051.       p++;
  1052.     }
  1053.       else if (whitespace (*p) || *p == '\n')
  1054.     {
  1055.       *r++ = '\'';
  1056.       *r++ = *p++;
  1057.       *r++ = '\'';
  1058.     }
  1059.       else
  1060.     *r++ = *p++;
  1061.     }
  1062.   *r++ = '\'';
  1063.   *r = '\0';
  1064.   return ret;
  1065. }
  1066. #endif /* SHELL */
  1067.  
  1068. static char *
  1069. hist_error(s, start, current, errtype)
  1070.       char *s;
  1071.       int start, current, errtype;
  1072. {
  1073.   char *temp, *emsg;
  1074.   int ll, elen;
  1075.  
  1076.   ll = current - start;
  1077.  
  1078.   switch (errtype)
  1079.     {
  1080.     case EVENT_NOT_FOUND:
  1081.       emsg = "event not found";
  1082.       elen = 15;
  1083.       break;
  1084.     case BAD_WORD_SPEC:
  1085.       emsg = "bad word specifier";
  1086.       elen = 18;
  1087.       break;
  1088.     case SUBST_FAILED:
  1089.       emsg = "substitution failed";
  1090.       elen = 19;
  1091.       break;
  1092.     case BAD_MODIFIER:
  1093.       emsg = "unrecognized history modifier";
  1094.       elen = 29;
  1095.       break;
  1096.     default:
  1097.       emsg = "unknown expansion error";
  1098.       elen = 23;
  1099.       break;
  1100.     }
  1101.  
  1102.   temp = xmalloc (ll + elen + 3);
  1103.   strncpy (temp, s + start, ll);
  1104.   temp[ll] = ':';
  1105.   temp[ll + 1] = ' ';
  1106.   strcpy (temp + ll + 2, emsg);
  1107.   return (temp);
  1108. }
  1109.  
  1110. /* Get a history substitution string from STR starting at *IPTR
  1111.    and return it.  The length is returned in LENPTR.
  1112.  
  1113.    A backslash can quote the delimiter.  If the string is the
  1114.    empty string, the previous pattern is used.  If there is
  1115.    no previous pattern for the lhs, the last history search
  1116.    string is used.
  1117.  
  1118.    If IS_RHS is 1, we ignore empty strings and set the pattern
  1119.    to "" anyway.  subst_lhs is not changed if the lhs is empty;
  1120.    subst_rhs is allowed to be set to the empty string. */
  1121.  
  1122. static char *
  1123. get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr)
  1124.      char *str;
  1125.      int *iptr, delimiter, is_rhs, *lenptr;
  1126. {
  1127.   register int si, i, j, k;
  1128.   char *s = (char *) NULL;
  1129.  
  1130.   i = *iptr;
  1131.  
  1132.   for (si = i; str[si] && str[si] != delimiter; si++)
  1133.     if (str[si] == '\\' && str[si + 1] == delimiter)
  1134.       si++;
  1135.  
  1136.   if (si > i || is_rhs)
  1137.     {
  1138.       s = xmalloc (si - i + 1);
  1139.       for (j = 0, k = i; k < si; j++, k++)
  1140.     {
  1141.       /* Remove a backslash quoting the search string delimiter. */
  1142.       if (str[k] == '\\' && str[k + 1] == delimiter)
  1143.         k++;
  1144.       s[j] = str[k];
  1145.     }
  1146.       s[j] = '\0';
  1147.       if (lenptr)
  1148.     *lenptr = j;
  1149.     }
  1150.  
  1151.   i = si;
  1152.   if (str[i])
  1153.     i++;
  1154.   *iptr = i;
  1155.  
  1156.   return s;
  1157. }
  1158.  
  1159. static void
  1160. postproc_subst_rhs ()
  1161. {
  1162.   char *new;
  1163.   int i, j, new_size;
  1164.  
  1165.   new = xmalloc (new_size = subst_rhs_len + subst_lhs_len);
  1166.   for (i = j = 0; i < subst_rhs_len; i++)
  1167.     {
  1168.       if (subst_rhs[i] == '&')
  1169.     {
  1170.       if (j + subst_lhs_len >= new_size)
  1171.         new = xrealloc (new, (new_size = new_size * 2 + subst_lhs_len));
  1172.       strcpy (new + j, subst_lhs);
  1173.       j += subst_lhs_len;
  1174.     }
  1175.       else
  1176.     {
  1177.       /* a single backslash protects the `&' from lhs interpolation */
  1178.       if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&')
  1179.         i++;
  1180.       if (j >= new_size)
  1181.         new = xrealloc (new, new_size *= 2);
  1182.       new[j++] = subst_rhs[i];
  1183.     }
  1184.     }
  1185.   new[j] = '\0';
  1186.   xfree (subst_rhs);
  1187.   subst_rhs = new;
  1188.   subst_rhs_len = j;
  1189. }
  1190.  
  1191. /* Expand the bulk of a history specifier starting at STRING[START].
  1192.    Returns 0 if everything is OK, -1 if an error occurred, and 1
  1193.    if the `p' modifier was supplied and the caller should just print
  1194.    the returned string.  Returns the new index into string in
  1195.    *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */
  1196. static int
  1197. history_expand_internal (string, start, end_index_ptr, ret_string, current_line)
  1198.      char *string;
  1199.      int start, *end_index_ptr;
  1200.      char **ret_string;
  1201.      char *current_line;        /* for !# */
  1202. {
  1203.   int i, n, starting_index;
  1204.   int substitute_globally, want_quotes, print_only;
  1205.   char *event, *temp, *result, *tstr, *t, c, *word_spec;
  1206.   int result_len;
  1207.  
  1208.   result = xmalloc (result_len = 128);
  1209.  
  1210.   i = start;
  1211.  
  1212.   /* If it is followed by something that starts a word specifier,
  1213.      then !! is implied as the event specifier. */
  1214.  
  1215.   if (member (string[i + 1], ":$*%^"))
  1216.     {
  1217.       char fake_s[3];
  1218.       int fake_i = 0;
  1219.       i++;
  1220.       fake_s[0] = fake_s[1] = history_expansion_char;
  1221.       fake_s[2] = '\0';
  1222.       event = get_history_event (fake_s, &fake_i, 0);
  1223.     }
  1224.   else if (string[i + 1] == '#')
  1225.     {
  1226.       i += 2;
  1227.       event = current_line;
  1228.     }
  1229.   else
  1230.     {
  1231.       int quoted_search_delimiter = 0;
  1232.  
  1233.       /* If the character before this `!' is a double or single
  1234.      quote, then this expansion takes place inside of the
  1235.      quoted string.  If we have to search for some text ("!foo"),
  1236.      allow the delimiter to end the search string. */
  1237.       if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  1238.     quoted_search_delimiter = string[i - 1];
  1239.       event = get_history_event (string, &i, quoted_search_delimiter);
  1240.     }
  1241.  
  1242.   if (!event)
  1243.     {
  1244.       *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND);
  1245.       xfree (result);
  1246.       return (-1);
  1247.     }
  1248.  
  1249.   /* If a word specifier is found, then do what that requires. */
  1250.   starting_index = i;
  1251.   word_spec = get_history_word_specifier (string, event, &i);
  1252.  
  1253.   /* There is no such thing as a `malformed word specifier'.  However,
  1254.      it is possible for a specifier that has no match.  In that case,
  1255.      we complain. */
  1256.   if (word_spec == (char *)&error_pointer)
  1257.     {
  1258.       *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC);
  1259.       xfree (result);
  1260.       return (-1);
  1261.     }
  1262.  
  1263.   /* If no word specifier, than the thing of interest was the event. */
  1264.   if (!word_spec)
  1265.     temp = savestring (event);
  1266.   else
  1267.     {
  1268.       temp = savestring (word_spec);
  1269.       xfree (word_spec);
  1270.     }
  1271.  
  1272.   /* Perhaps there are other modifiers involved.  Do what they say. */
  1273.   want_quotes = substitute_globally = print_only = 0;
  1274.   starting_index = i;
  1275.  
  1276.   while (string[i] == ':')
  1277.     {
  1278.       c = string[i + 1];
  1279.  
  1280.       if (c == 'g')
  1281.     {
  1282.       substitute_globally = 1;
  1283.       i++;
  1284.       c = string[i + 1];
  1285.     }
  1286.  
  1287.       switch (c)
  1288.     {
  1289.     default:
  1290.       *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER);
  1291.       xfree (result);
  1292.       xfree (temp);
  1293.       return -1;
  1294.  
  1295. #if defined (SHELL)
  1296.     case 'q':
  1297.       want_quotes = 'q';
  1298.       break;
  1299.  
  1300.     case 'x':
  1301.       want_quotes = 'x';
  1302.       break;
  1303. #endif /* SHELL */
  1304.  
  1305.       /* :p means make this the last executed line.  So we
  1306.          return an error state after adding this line to the
  1307.          history. */
  1308.     case 'p':
  1309.       print_only++;
  1310.       break;
  1311.  
  1312.       /* :t discards all but the last part of the pathname. */
  1313.     case 't':
  1314.       tstr = strrchr (temp, '/');
  1315.       if (tstr)
  1316.         {
  1317.           tstr++;
  1318.           t = savestring (tstr);
  1319.           xfree (temp);
  1320.           temp = t;
  1321.         }
  1322.       break;
  1323.  
  1324.       /* :h discards the last part of a pathname. */
  1325.     case 'h':
  1326.       tstr = strrchr (temp, '/');
  1327.       if (tstr)
  1328.         *tstr = '\0';
  1329.       break;
  1330.  
  1331.       /* :r discards the suffix. */
  1332.     case 'r':
  1333.       tstr = strrchr (temp, '.');
  1334.       if (tstr)
  1335.         *tstr = '\0';
  1336.       break;
  1337.  
  1338.       /* :e discards everything but the suffix. */
  1339.     case 'e':
  1340.       tstr = strrchr (temp, '.');
  1341.       if (tstr)
  1342.         {
  1343.           t = savestring (tstr);
  1344.           xfree (temp);
  1345.           temp = t;
  1346.         }
  1347.       break;
  1348.  
  1349.     /* :s/this/that substitutes `that' for the first
  1350.        occurrence of `this'.  :gs/this/that substitutes `that'
  1351.        for each occurrence of `this'.  :& repeats the last
  1352.        substitution.  :g& repeats the last substitution
  1353.        globally. */
  1354.  
  1355.     case '&':
  1356.     case 's':
  1357.       {
  1358.         char *new_event, *t;
  1359.         int delimiter, failed, si, l_temp;
  1360.  
  1361.         if (c == 's')
  1362.           {
  1363.         if (i + 2 < (int)strlen (string))
  1364.           delimiter = string[i + 2];
  1365.         else
  1366.           break;        /* no search delimiter */
  1367.  
  1368.         i += 3;
  1369.  
  1370.         t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len);
  1371.         /* An empty substitution lhs with no previous substitution
  1372.            uses the last search string as the lhs. */
  1373.         if (t)
  1374.           {
  1375.             if (subst_lhs)
  1376.               xfree (subst_lhs);
  1377.             subst_lhs = t;
  1378.           }
  1379.         else if (!subst_lhs)
  1380.           {
  1381.             if (search_string && *search_string)
  1382.               {
  1383.             subst_lhs = savestring (search_string);
  1384.             subst_lhs_len = strlen (subst_lhs);
  1385.               }
  1386.             else
  1387.               {
  1388.             subst_lhs = (char *) NULL;
  1389.             subst_lhs_len = 0;
  1390.               }
  1391.           }
  1392.  
  1393.         /* If there is no lhs, the substitution can't succeed. */
  1394.         if (subst_lhs_len == 0)
  1395.           {
  1396.             *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1397.             xfree (result);
  1398.             xfree (temp);
  1399.             return -1;
  1400.           }
  1401.  
  1402.         if (subst_rhs)
  1403.           xfree (subst_rhs);
  1404.         subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len);
  1405.  
  1406.         /* If `&' appears in the rhs, it's supposed to be replaced
  1407.            with the lhs. */
  1408.         if (member ('&', subst_rhs))
  1409.           postproc_subst_rhs ();
  1410.           }
  1411.         else
  1412.           i += 2;
  1413.  
  1414.         l_temp = strlen (temp);
  1415.         /* Ignore impossible cases. */
  1416.         if (subst_lhs_len > l_temp)
  1417.           {
  1418.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1419.         xfree (result);
  1420.         xfree (temp);
  1421.         return (-1);
  1422.           }
  1423.  
  1424.         /* Find the first occurrence of THIS in TEMP. */
  1425.         si = 0;
  1426.         for (failed = 1; (si + subst_lhs_len) <= l_temp; si++)
  1427.           if (STREQN (temp+si, subst_lhs, subst_lhs_len))
  1428.         {
  1429.           int len = subst_rhs_len - subst_lhs_len + l_temp;
  1430.           new_event = xmalloc (1 + len);
  1431.           strncpy (new_event, temp, si);
  1432.           strncpy (new_event + si, subst_rhs, subst_rhs_len);
  1433.           strncpy (new_event + si + subst_rhs_len,
  1434.                temp + si + subst_lhs_len,
  1435.                l_temp - (si + subst_lhs_len));
  1436.           new_event[len] = '\0';
  1437.           xfree (temp);
  1438.           temp = new_event;
  1439.  
  1440.           failed = 0;
  1441.  
  1442.           if (substitute_globally)
  1443.             {
  1444.               si += subst_rhs_len;
  1445.               l_temp = strlen (temp);
  1446.               substitute_globally++;
  1447.               continue;
  1448.             }
  1449.           else
  1450.             break;
  1451.         }
  1452.  
  1453.         if (substitute_globally > 1)
  1454.           {
  1455.         substitute_globally = 0;
  1456.         continue;       /* don't want to increment i */
  1457.           }
  1458.  
  1459.         if (failed == 0)
  1460.           continue;         /* don't want to increment i */
  1461.  
  1462.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1463.         xfree (result);
  1464.         xfree (temp);
  1465.         return (-1);
  1466.       }
  1467.     }
  1468.       i += 2;
  1469.     }
  1470.   /* Done with modfiers. */
  1471.   /* Believe it or not, we have to back the pointer up by one. */
  1472.   --i;
  1473.  
  1474. #if defined (SHELL)
  1475.   if (want_quotes)
  1476.     {
  1477.       char *x;
  1478.  
  1479.       if (want_quotes == 'q')
  1480.     x = single_quote (temp);
  1481.       else if (want_quotes == 'x')
  1482.     x = quote_breaks (temp);
  1483.       else
  1484.     x = savestring (temp);
  1485.  
  1486.       xfree (temp);
  1487.       temp = x;
  1488.     }
  1489. #endif /* SHELL */
  1490.  
  1491.   n = strlen (temp);
  1492.   if (n > result_len)
  1493.     result = xrealloc (result, n + 1);
  1494.   strcpy (result, temp);
  1495.   xfree (temp);
  1496.  
  1497.   *end_index_ptr = i;
  1498.   *ret_string = result;
  1499.   return (print_only);
  1500. }
  1501.  
  1502. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  1503.    to a string.  Returns:
  1504.  
  1505.   -1) If there was an error in expansion.
  1506.    0) If no expansions took place (or, if the only change in
  1507.       the text was the de-slashifying of the history expansion
  1508.       character)
  1509.    1) If expansions did take place
  1510.    2) If the `p' modifier was given and the caller should print the result
  1511.  
  1512.   If an error ocurred in expansion, then OUTPUT contains a descriptive
  1513.   error message. */
  1514.  
  1515. #define ADD_STRING(s) \
  1516.     do \
  1517.       { \
  1518.         int sl = strlen (s); \
  1519.         j += sl; \
  1520.         while (j >= result_len) \
  1521.           result = xrealloc (result, result_len += 128); \
  1522.         strcpy (result + j - sl, s); \
  1523.       } \
  1524.     while (0)
  1525.  
  1526. #define ADD_CHAR(c) \
  1527.     do \
  1528.       { \
  1529.         if (j >= result_len) \
  1530.           result = xrealloc (result, result_len += 64); \
  1531.         result[j++] = c; \
  1532.         result[j] = '\0'; \
  1533.       } \
  1534.     while (0)
  1535.  
  1536. int
  1537. history_expand (hstring, output)
  1538.      char *hstring;
  1539.      char **output;
  1540. {
  1541.   register int j;
  1542.   int i, r, l, passc, cc, modified, eindex, only_printing;
  1543.   char *string;
  1544.  
  1545.   /* The output string, and its length. */
  1546.   int result_len;
  1547.   char *result;
  1548.  
  1549.   /* Used when adding the string. */
  1550.   char *temp;
  1551.  
  1552.   /* Setting the history expansion character to 0 inhibits all
  1553.      history expansion. */
  1554.   if (history_expansion_char == 0)
  1555.     {
  1556.       *output = savestring (hstring);
  1557.       return (0);
  1558.     }
  1559.  
  1560.   /* Prepare the buffer for printing error messages. */
  1561.   result = xmalloc (result_len = 256);
  1562.   result[0] = '\0';
  1563.  
  1564.   only_printing = modified = 0;
  1565.   l = strlen (hstring);
  1566.  
  1567.   /* Grovel the string.  Only backslash can quote the history escape
  1568.      character.  We also handle arg specifiers. */
  1569.  
  1570.   /* Before we grovel forever, see if the history_expansion_char appears
  1571.      anywhere within the text. */
  1572.  
  1573.   /* The quick substitution character is a history expansion all right.  That
  1574.      is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  1575.      that is the substitution that we do. */
  1576.   if (hstring[0] == history_subst_char)
  1577.     {
  1578.       string = xmalloc (l + 5);
  1579.  
  1580.       string[0] = string[1] = history_expansion_char;
  1581.       string[2] = ':';
  1582.       string[3] = 's';
  1583.       strcpy (string + 4, hstring);
  1584.       l += 4;
  1585.     }
  1586.   else
  1587.     {
  1588.       string = hstring;
  1589.       /* If not quick substitution, still maybe have to do expansion. */
  1590.  
  1591.       /* `!' followed by one of the characters in history_no_expand_chars
  1592.      is NOT an expansion. */
  1593.       for (i = 0; string[i]; i++)
  1594.     {
  1595.       cc = string[i + 1];
  1596.       if (string[i] == history_expansion_char)
  1597.         {
  1598.           if (!cc || member (cc, history_no_expand_chars))
  1599.         continue;
  1600. #if defined (SHELL)
  1601.           /* The shell uses ! as a pattern negation character
  1602.          in globbing [...] expressions, so let those pass
  1603.          without expansion. */
  1604.           else if (i > 0 && (string[i - 1] == '[') &&
  1605.                member (']', string + i + 1))
  1606.         continue;
  1607. #endif /* SHELL */
  1608.           else
  1609.         break;
  1610.         }
  1611. #if defined (SHELL)
  1612.       else if (string[i] == '\'')
  1613.         {
  1614.           /* If this is bash, single quotes inhibit history expansion. */
  1615.           i++;
  1616.           rl_string_extract_single_quoted (string, &i);
  1617.         }
  1618.       else if (string[i] == '\\')
  1619.         {
  1620.           /* If this is bash, allow backslashes to quote single
  1621.          quotes and
  1622.          the history expansion character. */
  1623.           if (cc == '\'' || cc == history_expansion_char)
  1624.         i++;
  1625.         }
  1626. #endif /* SHELL */
  1627.     }
  1628.  
  1629.       if (string[i] != history_expansion_char)
  1630.     {
  1631.       xfree (result);
  1632.       *output = savestring (string);
  1633.       return (0);
  1634.     }
  1635.     }
  1636.  
  1637.   /* Extract and perform the substitution. */
  1638.   for (passc = i = j = 0; i < l; i++)
  1639.     {
  1640.       int tchar = string[i];
  1641.  
  1642.       if (passc)
  1643.     {
  1644.       passc = 0;
  1645.       ADD_CHAR (tchar);
  1646.       continue;
  1647.     }
  1648.  
  1649.       if (tchar == history_expansion_char)
  1650.     tchar = -3;
  1651.  
  1652.       switch (tchar)
  1653.     {
  1654.     default:
  1655.       ADD_CHAR (string[i]);
  1656.       break;
  1657.  
  1658.     case '\\':
  1659.       passc++;
  1660.       ADD_CHAR (tchar);
  1661.       break;
  1662.  
  1663. #if defined (SHELL)
  1664.     case '\'':
  1665.       {
  1666.         /* If this is bash, single quotes inhibit history expansion. */
  1667.         int quote, slen;
  1668.  
  1669.         quote = i++;
  1670.         rl_string_extract_single_quoted (string, &i);
  1671.  
  1672.         slen = i - quote + 2;
  1673.         temp = xmalloc (slen);
  1674.         strncpy (temp, string + quote, slen);
  1675.         temp[slen - 1] = '\0';
  1676.         ADD_STRING (temp);
  1677.         xfree (temp);
  1678.         break;
  1679.       }
  1680. #endif /* SHELL */
  1681.  
  1682.     case -3:                /* history_expansion_char */
  1683.       cc = string[i + 1];
  1684.  
  1685.       /* If the history_expansion_char is followed by one of the
  1686.          characters in history_no_expand_chars, then it is not a
  1687.          candidate for expansion of any kind. */
  1688.       if (member (cc, history_no_expand_chars))
  1689.         {
  1690.           ADD_CHAR (string[i]);
  1691.           break;
  1692.         }
  1693.  
  1694. #if defined (NO_BANG_HASH_MODIFIERS)
  1695.       /* There is something that is listed as a `word specifier' in csh
  1696.          documentation which means `the expanded text to this point'.
  1697.          That is not a word specifier, it is an event specifier.  If we
  1698.          don't want to allow modifiers with `!#', just stick the current
  1699.          output line in again. */
  1700.       if (cc == '#')
  1701.         {
  1702.           if (result)
  1703.         {
  1704.           temp = xmalloc (1 + strlen (result));
  1705.           strcpy (temp, result);
  1706.           ADD_STRING (temp);
  1707.           xfree (temp);
  1708.         }
  1709.           i++;
  1710.           break;
  1711.         }
  1712. #endif
  1713.  
  1714.       r = history_expand_internal (string, i, &eindex, &temp, result);
  1715.       if (r < 0)
  1716.         {
  1717.           *output = temp;
  1718.           xfree (result);
  1719.           if (string != hstring)
  1720.         xfree (string);
  1721.           return -1;
  1722.         }
  1723.       else
  1724.         {
  1725.           if (temp)
  1726.         {
  1727.           modified++;
  1728.           if (*temp)
  1729.             ADD_STRING (temp);
  1730.           xfree (temp);
  1731.         }
  1732.           only_printing = r == 1;
  1733.           i = eindex;
  1734.         }
  1735.       break;
  1736.     }
  1737.     }
  1738.  
  1739.   *output = result;
  1740.   if (string != hstring)
  1741.     xfree (string);
  1742.  
  1743.   if (only_printing)
  1744.     {
  1745.       add_history (result);
  1746.       return (2);
  1747.     }
  1748.  
  1749.   return (modified != 0);
  1750. }
  1751.  
  1752. /* Return a consed string which is the word specified in SPEC, and found
  1753.    in FROM.  NULL is returned if there is no spec.  The address of
  1754.    ERROR_POINTER is returned if the word specified cannot be found.
  1755.    CALLER_INDEX is the offset in SPEC to start looking; it is updated
  1756.    to point to just after the last character parsed. */
  1757. static char *
  1758. get_history_word_specifier (spec, from, caller_index)
  1759.      char *spec, *from;
  1760.      int *caller_index;
  1761. {
  1762.   register int i = *caller_index;
  1763.   int first, last;
  1764.   int expecting_word_spec = 0;
  1765.   char *result;
  1766.  
  1767.   /* The range of words to return doesn't exist yet. */
  1768.   first = last = 0;
  1769.   result = (char *)NULL;
  1770.  
  1771.   /* If we found a colon, then this *must* be a word specification.  If
  1772.      it isn't, then it is an error. */
  1773.   if (spec[i] == ':')
  1774.     {
  1775.       i++;
  1776.       expecting_word_spec++;
  1777.     }
  1778.  
  1779.   /* Handle special cases first. */
  1780.  
  1781.   /* `%' is the word last searched for. */
  1782.   if (spec[i] == '%')
  1783.     {
  1784.       *caller_index = i + 1;
  1785.       return (search_string ? savestring (search_string) : savestring (""));
  1786.     }
  1787.  
  1788.   /* `*' matches all of the arguments, but not the command. */
  1789.   if (spec[i] == '*')
  1790.     {
  1791.       *caller_index = i + 1;
  1792.       result = history_arg_extract (1, '$', from);
  1793.       return (result ? result : savestring (""));
  1794.     }
  1795.  
  1796.   /* `$' is last arg. */
  1797.   if (spec[i] == '$')
  1798.     {
  1799.       *caller_index = i + 1;
  1800.       return (history_arg_extract ('$', '$', from));
  1801.     }
  1802.  
  1803.   /* Try to get FIRST and LAST figured out. */
  1804.  
  1805.   if (spec[i] == '-')
  1806.     first = 0;
  1807.   else if (spec[i] == '^')
  1808.     first = 1;
  1809.   else if (digit (spec[i]) && expecting_word_spec)
  1810.     {
  1811.       for (first = 0; digit (spec[i]); i++)
  1812.     first = (first * 10) + digit_value (spec[i]);
  1813.     }
  1814.   else
  1815.     return ((char *)NULL);      /* no valid `first' for word specifier */
  1816.  
  1817.   if (spec[i] == '^' || spec[i] == '*')
  1818.     {
  1819.       last = (spec[i] == '^') ? 1 : '$';        /* x* abbreviates x-$ */
  1820.       i++;
  1821.     }
  1822.   else if (spec[i] != '-')
  1823.     last = first;
  1824.   else
  1825.     {
  1826.       i++;
  1827.  
  1828.       if (digit (spec[i]))
  1829.     {
  1830.       for (last = 0; digit (spec[i]); i++)
  1831.         last = (last * 10) + digit_value (spec[i]);
  1832.     }
  1833.       else if (spec[i] == '$')
  1834.     {
  1835.       i++;
  1836.       last = '$';
  1837.     }
  1838.       else if (!spec[i] || spec[i] == ':')  /* could be modifier separator */
  1839.     last = -1;              /* x- abbreviates x-$ omitting word `$' */
  1840.     }
  1841.  
  1842.   *caller_index = i;
  1843.  
  1844.   if (last >= first || last == '$' || last < 0)
  1845.     result = history_arg_extract (first, last, from);
  1846.  
  1847.   return (result ? result : (char *)&error_pointer);
  1848. }
  1849.  
  1850. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1851.    The args are taken from STRING.  If either FIRST or LAST is < 0,
  1852.    then make that arg count from the right (subtract from the number of
  1853.    tokens, so that FIRST = -1 means the next to last token on the line).
  1854.    If LAST is `$' the last arg from STRING is used. */
  1855. char *
  1856. history_arg_extract (first, last, string)
  1857.      int first, last;
  1858.      char *string;
  1859. {
  1860.   register int i, len;
  1861.   char *result = (char *)NULL;
  1862.   int size = 0, offset = 0;
  1863.   char **list;
  1864.  
  1865.   /* XXX - think about making history_tokenize return a struct array,
  1866.      each struct in array being a string and a length to avoid the
  1867.      calls to strlen below. */
  1868.   if ((list = history_tokenize (string)) == NULL)
  1869.     return ((char *)NULL);
  1870.  
  1871.   for (len = 0; list[len]; len++)
  1872.     ;
  1873.  
  1874.   if (last < 0)
  1875.     last = len + last - 1;
  1876.  
  1877.   if (first < 0)
  1878.     first = len + first - 1;
  1879.  
  1880.   if (last == '$')
  1881.     last = len - 1;
  1882.  
  1883.   if (first == '$')
  1884.     first = len - 1;
  1885.  
  1886.   last++;
  1887.  
  1888.   if (first > len || last > len || first < 0 || last < 0)
  1889.     result = ((char *)NULL);
  1890.   else
  1891.     {
  1892.       for (size = 0, i = first; i < last; i++)
  1893.     size += strlen (list[i]) + 1;
  1894.       result = xmalloc (size + 1);
  1895.  
  1896.       for (i = first; i < last; i++)
  1897.     {
  1898.       strcpy (result + offset, list[i]);
  1899.       offset += strlen (list[i]);
  1900.       if (i + 1 < last)
  1901.         {
  1902.           result[offset++] = ' ';
  1903.           result[offset] = 0;
  1904.         }
  1905.     }
  1906.     }
  1907.  
  1908.   for (i = 0; i < len; i++)
  1909.     xfree (list[i]);
  1910.   xfree (list);
  1911.  
  1912.   return (result);
  1913. }
  1914.  
  1915. #define slashify_in_quotes "\\`\"$"
  1916.  
  1917. /* Return an array of tokens, much as the shell might.  The tokens are
  1918.    parsed out of STRING. */
  1919. char **
  1920. history_tokenize (string)
  1921.      char *string;
  1922. {
  1923.   char **result = (char **)NULL;
  1924.   register int i, start, result_index, size;
  1925.   int len;
  1926.  
  1927.   i = result_index = size = 0;
  1928.  
  1929.   /* Get a token, and stuff it into RESULT.  The tokens are split
  1930.      exactly where the shell would split them. */
  1931.   while (string[i])
  1932.     {
  1933.       int delimiter = 0;
  1934.  
  1935.       /* Skip leading whitespace. */
  1936.       for (; string[i] && whitespace (string[i]); i++)
  1937.     ;
  1938.       if (!string[i] || string[i] == history_comment_char)
  1939.     return (result);
  1940.  
  1941.       start = i;
  1942.  
  1943.       if (member (string[i], "()\n"))
  1944.     {
  1945.       i++;
  1946.       goto got_token;
  1947.     }
  1948.  
  1949.       if (member (string[i], "<>;&|$"))
  1950.     {
  1951.       int peek = string[i + 1];
  1952.  
  1953.       if (peek == string[i] && peek != '$')
  1954.         {
  1955.           if (peek == '<' && string[i + 2] == '-')
  1956.         i++;
  1957.           i += 2;
  1958.           goto got_token;
  1959.         }
  1960.       else
  1961.         {
  1962.           if ((peek == '&' && (string[i] == '>' || string[i] == '<')) ||
  1963.           ((peek == '>') && (string[i] == '&')) ||
  1964.           ((peek == '(') && (string[i] == '$')))
  1965.         {
  1966.           i += 2;
  1967.           goto got_token;
  1968.         }
  1969.         }
  1970.       if (string[i] != '$')
  1971.         {
  1972.           i++;
  1973.           goto got_token;
  1974.         }
  1975.     }
  1976.  
  1977.       /* Get word from string + i; */
  1978.  
  1979.       if (member (string[i], "\"'`"))
  1980.     delimiter = string[i++];
  1981.  
  1982.       for (; string[i]; i++)
  1983.     {
  1984.       if (string[i] == '\\' && string[i + 1] == '\n')
  1985.         {
  1986.           i++;
  1987.           continue;
  1988.         }
  1989.  
  1990.       if (string[i] == '\\' && delimiter != '\'' &&
  1991.           (delimiter != '"' || member (string[i], slashify_in_quotes)))
  1992.         {
  1993.           i++;
  1994.           continue;
  1995.         }
  1996.  
  1997.       if (delimiter && string[i] == delimiter)
  1998.         {
  1999.           delimiter = 0;
  2000.           continue;
  2001.         }
  2002.  
  2003.       if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  2004.         break;
  2005.  
  2006.       if (!delimiter && member (string[i], "\"'`"))
  2007.         delimiter = string[i];
  2008.     }
  2009.     got_token:
  2010.  
  2011.       len = i - start;
  2012.       if (result_index + 2 >= size)
  2013.     result = (char **)xrealloc (result, ((size += 10) * sizeof (char *)));
  2014.       result[result_index] = xmalloc (1 + len);
  2015.       strncpy (result[result_index], string + start, len);
  2016.       result[result_index][len] = '\0';
  2017.       result[++result_index] = (char *)NULL;
  2018.     }
  2019.  
  2020.   return (result);
  2021. }
  2022.